import React, { useState, useEffect, useRef } from 'react';
import './index.scss'
import { useNavigate } from 'react-router-dom';
import money from '../../../img/money.png'
import axios from 'axios';
import { Input, Button, DatePicker, Select, Table, Pagination, ConfigProvider } from 'antd';
import { CaretDownOutlined, CaretUpOutlined } from "@ant-design/icons"
import type { ColumnsType } from 'antd/es/table';
import { useDispatch, useSelector } from 'react-redux';
// 日期选择器中文
import 'moment/locale/zh-cn';
import locale from 'antd/lib/date-picker/locale/zh_CN';
// // 分页中文
import zhCN from 'antd/es/locale/zh_CN'

const { Search } = Input;

const Financemanage = () => {
    // 发请求
    useEffect(() => {
        requestPort();
        requestOrder();
    }, [])
    let requestPort = () => {
        //测试GET
        axios.get("http://localhost:3000/dayCount").then((res) => {
            console.log(res.data);
            if (res.status == 200) {
                console.log(res.data);
                setcounts(res.data)
            }
        }).catch((err) => {
            console.warn(err);
        }).then(function () {
            // 总是会执行
        });;
    }
    let requestOrder = () => {
        //测试GET
        axios.get("http://localhost:3000/order").then((res) => {
            if (res.status == 200) {
                console.log(res.data);
                setdata(res.data)
                setlength(res.data.length)
                dispatch({ type: 'CUN', payload: res.data })
                // console.log(res.data.length);
            }
        })
    }
    // 定义响应式数据
    let [port, setport] = useState();
    let [order, setorder] = useState();
    let [select, setselect] = useState(true);
    let [length, setlength] = useState(0);
    let minimoney = useRef(null);
    let maxmoney = useRef(null);
    let [data, setdata] = useState([]);
    let [counts, setcounts] = useState([])
    let navigate = useNavigate()
    // 存
    let dispatch = useDispatch()
    // 取
    let storedata = useSelector((state: any) => state.financemanage)

    let [pageSize, setpageSize] = useState(5)
    let [dateStringVal, setdateStringVal] = useState(String)
    let [selectedVal, setselectedVal] = useState(String)
    let [moneyPrv, setmoneyPrv]: any = useState()
    let [moneyLast, setmoneyLast]: any = useState()
    // 搜索框(模糊查询)
    const onSearch = (value: string) => {
        // 有内容查询，无内容就直接存（解决没内容也触发查询）
        if (value || dateStringVal || selectedVal || moneyPrv || moneyLast) {
            // 返回模糊查询符合条件的数组
            let newdata: any = storedata.filter((item: any) => {
                return item.userName == value || item.orderNumber == value || item.transactionSerialNumber == value || item.time == dateStringVal || item.payType == selectedVal || moneyPrv * 1 <= item.money * 1 && item.money * 1 <= moneyLast * 1
                // return item.userName.includes(value) || item.orderNumber.indexOf(value) !== -1 || item.transactionSerialNumber.indexOf(value) !== -1
            })
            // console.log(newdata);
            // 更新查询的
            setdata(newdata)
        } else if (!value && !dateStringVal && !selectedVal && !moneyPrv && !moneyLast) {
            setdata(storedata)
        }
    }
    // select下拉菜单项
    const changeSelect = () => {
        setselect(!select)
    }
    // 日历
    const onChange = (date: any, dateString: any) => {
        // console.log(dateString); //2023-05-10
        setdateStringVal(dateString)
    };
    // select选择
    const handleChange = (value: string) => {
        // console.log(`selected ${value}`); // 类型
        setselectedVal(value)
    };
    // 金额区间
    let inputVal = (e: any) => {
        if (e.target.name == 'input1') {
            // console.log(e.target.value);
            setmoneyPrv(e.target.value)
        } else {
            setmoneyLast(e.target.value)
        }
    }
    // 表格操作：：：
    let onOrderNumber = (id: any) => {
        // 根据id跳转到对应的订单号页面
    }
    // 表格：：：
    interface DataType {
        id: number;
        time: string;
        userName: string;
        orderNumber: string;
        transactionSerialNumber: string;
        payType: string;
        money: number
    }
    const columns: ColumnsType<DataType> = [
        // {
        //     title: '序号',
        //     dataIndex: 'xu',
        //     key: 'xu',
        //     render: (text, record, index) => {
        //         return <>{index + 1}</>
        //     }
        // },
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '交易时间',
            dataIndex: 'time',
            key: 'time',
        },
        {
            title: '用户昵称',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '订单号',
            dataIndex: 'orderNumber',
            key: 'orderNumber',
            render: (text, record, index) => {
                return <span style={{ color: "blue" }} onClick={(record: any) => { onOrderNumber(record.id) }}>{record.orderNumber}</span>
            }
        },
        {
            title: '交易流水号',
            dataIndex: 'transactionSerialNumber',
            key: 'transactionSerialNumber',
        },
        {
            title: '交易类型',
            dataIndex: 'payType',
            key: 'payType',
            render: (text, record: any, index) => {
                // 这里判断状态：0绿色支付，1退款橙色
                if (record.payType == "付款") {
                    return (<span style={{ color: "green" }}>付款</span>)
                } else if (record.payType == "退款") {
                    return (<span style={{ color: "red" }}>退款</span>)
                } else if (record.payType == "未评价") {
                    return (<span style={{ color: "yellow" }}>未评价</span>)
                } else if (record.payType == "已评价") {
                    return (<span style={{ color: "green" }}>已评价</span>)
                } else if (record.payType == "超时评价") {
                    return (<span style={{ color: "red" }}>超时评价</span>)
                }
                // return <>
                //     {
                //         record.payType == "付款" ?
                //             <span style={{ color: "green" }}>付款</span>
                //             : <span style={{ color: "orange" }}>退款</span>
                //     }
                // </>
            }

        },
        {
            title: '金额',
            dataIndex: 'money',
            key: 'money',
        },
    ];

    return (
        <div className='recomlist'>
            {
                counts.map((item: any) => {
                    return (
                        <div className='count' key={item.id}>
                            <div><p>￥{item.today}</p><p>今日订单收入</p>  <img src={money} alt="money"></img></div>
                            <div><p>￥{item.yesterday}</p><p>昨天订单收入</p> <img src={money} alt="money"></img></div>
                            <div><p>￥{item.count}</p><p>累计订单收入</p> <img src={money} alt="money"></img></div>
                        </div>
                    )
                })
            }
            <div className='search'>
                <Search style={{ width: "350px", marginRight: '30px' }} placeholder="输入用户昵称、订单号或者交易流水号" onSearch={onSearch} enterButton={"搜索"} />
                <Button onClick={() => { changeSelect() }} style={{ color: '#438dee', borderColor: '#438dee' }}>
                    更多筛选项 {select ? <CaretDownOutlined /> : <CaretUpOutlined />}
                </Button>
            </div>
            {/* <div className={`${select? "search_hidden":"search_hidden.active"}`}> */}
            <div className='search_hidden' style={select ? { height: "0px" } : { height: '50px' }}>
                <span>时间段：
                    <DatePicker locale={locale} onChange={onChange} placeholder="年/月/日" />
                </span>
                <span>交易类型：
                    <Select
                        onChange={handleChange}
                        defaultValue="全部"
                        style={{ width: 120 }}
                        options={[
                            { value: '全部', label: '全部' },
                            { value: '未评价', label: '未评价' },
                            { value: '已评价', label: '已评价' },
                            { value: '超时评价', label: '超时评价' },
                            { value: '付款', label: '付款' },
                            { value: '退款', label: '退款' },
                        ]}
                    />
                </span>
                <span>金额区间：
                    <Input placeholder="最低金额" style={{ width: "100px" }} ref={minimoney} name={"input1"} onChange={(e) => { inputVal(e) }} />
                    &nbsp;&nbsp; - &nbsp;&nbsp;
                    <Input placeholder="最高金额" style={{ width: "100px" }} ref={maxmoney} name={"input2"} onChange={(e) => { inputVal(e) }} />
                </span>
            </div>
            <div className='table'>
                {/* 中文 */}
                <ConfigProvider locale={zhCN}>
                    <Table columns={columns} dataSource={data}
                        rowKey={record => record.id}
                        // 分页：：：
                        pagination={{
                            pageSize: pageSize,    //每页多少条
                            total: length,    //一共多少条，可以决定分页的条数
                            pageSizeOptions: ['5', '10', '20'],
                            onShowSizeChange: (current, size) => setpageSize(size), //console.log(current,size),//curren:页码，sizi选择一页多少条

                            showQuickJumper: true,    //是否有跳转到第几页
                            showSizeChanger: true, //是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
                            showTotal: total => `共${length}条`,     //自定义成中文共多少条
                            // onChange:function(page, pageSize)
                        }}
                        onRow={(record) => {
                            return {
                                onClick: (event) => {
                                    console.log(11111111);
                                    // 待定：：：
                                    navigate("/index/commanage")
                                }, // 点击行。进行跳路由操作
                            };
                        }}
                    />
                </ConfigProvider>
            </div>
        </div>
    );
};

export default Financemanage;